/**
 * 
 */
package com.geekteam.geometrychess.handler.event;

import java.util.List;

import com.geekteam.geometrychess.board.GameBoard;
import com.geekteam.geometrychess.extension.ChessExtension;
import com.geekteam.geometrychess.room.entity.Player;
import com.geekteam.geometrychess.utils.Code;
import com.geekteam.geometrychess.utils.Commands;
import com.geekteam.geometrychess.utils.Constants;
import com.geekteam.geometrychess.utils.Message;
import com.geekteam.geometrychess.utils.Utils;
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSArray;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;

/**
 * @author MtRol
 * 
 */
public class JoinRoomEventHandler extends BaseServerEventHandler {
	private Room mRoom;
	private User mUser;
	private Player mPlayer;
	private ChessExtension mExtension;

	@Override
	public void handleServerEvent(ISFSEvent event) throws SFSException {
		mRoom = (Room) event.getParameter(SFSEventParam.ROOM);
		mUser = (User) event.getParameter(SFSEventParam.USER);
		mExtension = (ChessExtension) this.getParentExtension();
		mPlayer = Utils.getPlayerFromSFSUser(mUser);
		if (mPlayer == null) {
			mExtension.sendPrivateError(Code.USER_NOT_FOUND,
					Message.USER_NOT_FOUND, mUser.getId());
			return;
		}

		if (mRoom == null) {
			mExtension.sendPrivateError(Code.ROOM_NOT_FOUND,
					Message.USER_NOT_FOUND, mUser.getId());
			return;
		}

		// leave last join room before join new room
		if (mUser.getLastJoinedRoom() != null) {
			getApi().leaveRoom(mUser, mUser.getLastJoinedRoom());
		}

		// gui thong tin cua minh ve cho nguoi choi va gui thong tin cua nguoi
		// choi lan cua minh ve cho minh
		if (mRoom.isGame()) {
			// TODO handler with room game

			// check condition here
			if (!checkConditionBeforeJoinRoom()) {
				mExtension.sendPrivateError(Code.FAILED, "", mUser.getId());
				return;
			}

			GameBoard board = mExtension.getBoard(mRoom.getId());
			// khoi tao ban choi neu nhu null
			if (board == null) {
				board = new GameBoard(mRoom.getId(), mRoom.getName());
				mExtension.addBoard(mRoom.getId(), board);
			}
			// getApi().joinRoom(mUser, mRoom);
			// add player to game
			board.getRoomBoard().addPlayer(mPlayer);
			// object to send list user in room
			ISFSObject userObject = mPlayer.toSFSObjectFull();
			// object to send player
			ISFSObject ListUserObject = board.getJoinRoomObject();

			List<User> listUser = mRoom.getUserList();
			// send to player
			send(Commands.JOIN_ROOM_SUCCESS, ListUserObject, mUser);
			// send to list player in room
			send(Commands.NEW_USER_JOIN_ROOM, userObject, listUser);
			// send to player in lobby room
			List<User> waittingList = mExtension.getParentZone()
					.getRoomByName(Constants.publicRoom).getUserList();
			send(Commands.UPDATE_LIST_WAITING, mPlayer.toLobbyObject(),
					waittingList);
		} else {
			mRoom.addUser(mUser);
			List<User> waittingList = mRoom.getUserList();
			ISFSObject lobbyObject = new SFSObject();
			for (User user : waittingList) {
				trace("User in waitting room : " + user.getName());
				Player player = mExtension.getPlayerBySFSId(user.getId());
				if (player != null) {
					ISFSObject object = player.toSFSObjectSimple();
					trace(object.toJson());
					lobbyObject.putSFSObject(user.getName(), object);
				}
			}
			// send danh sach nguoi cho trong phong cho
			send(Commands.LOBBY_WAITING, lobbyObject, mUser);

			// send thong tin nguoi choi cho nhung ngui trong phong cho biet
			// object nay chua thong tin nguoi choi va bien boolean xac dinh la
			// add nguoi choi vao hay la remove nguoi choi di
			ISFSObject waittingObject = new SFSObject();
			waittingObject.putBool("isAdd", true);
			waittingObject.putSFSObject("user", mPlayer.toSFSObjectSimple());
			send(Commands.UPDATE_LIST_WAITING, waittingObject, waittingList);
			
			//gui ve danh sach ban choi va nguoi nguoi o trong do
			String groupId = mRoom.getGroupId();
			List<Room> rooms = mExtension.getParentZone().getRoomListFromGroup(groupId);
			SFSObject roomObject = new SFSObject();
			SFSArray roomArray = new SFSArray();
			for(Room room:rooms){
				if(room.isGame()){
					SFSObject object = new SFSObject();
					object.putUtfString("name", room.getName());
					object.putInt("id", room.getId());
					List<User> users = room.getPlayersList();
					SFSArray array = new SFSArray();
					if(users!=null){
						for(User user : users){
							Player p = Utils.getPlayerFromSFSUser(user);
							array.addSFSObject(p.toSFSObjectSimple());
						}
					}
					object.putSFSArray("players", array);
					roomArray.addSFSObject(object);
				}
			}
			roomObject.putSFSArray("rooms", roomArray);
			//send list room
			send(Commands.LIST_ROOM, roomObject, mUser);
		}
	}

	private boolean checkConditionBeforeJoinRoom() {

		return true;
	}
}
